package logic

import (
	"context"
	"errors"
	"mall_srv/cache"
	"mall_srv/models"

	"mall_srv/good"
	"mall_srv/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CartAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCartAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CartAddLogic {
	return &CartAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 添加购物车
func (l *CartAddLogic) CartAdd(in *good.CartAddRequest) (*good.CartAddResponse, error) {
	// todo: add your logic here and delete this line
	var err error
	//判断用户是否存在
	var u models.User
	u.ID = uint(in.UserId)
	if err = u.UserShow(); err != nil {
		logx.Info("用户不存在")
		return nil, errors.New("用户不存在")
	}
	//判断商品是否存在
	var g models.Goods
	g.ID = uint(in.GoodsId)
	if err = g.GoodsShow(); err != nil {
		logx.Info("商品不存在")
		return nil, errors.New("商品不存在")
	}
	//库存是否充足
	if g.GoodsStock < in.Num {
		logx.Info("库存不足")
		return nil, errors.New("库存不足")
	}
	//添加购物车
	goodsMap := map[string]interface{}{
		"userId":  in.UserId,
		"goodsId": in.GoodsId,
		"num":     in.Num,
		"title":   g.GoodsTitle,
		"image":   g.GoodsImage,
		"price":   g.GoodsPrice,
	}
	err = cache.CartAdd(int(in.UserId), int(in.GoodsId), goodsMap)
	if err != nil {
		logx.Info("添加购物车失败", err)
		return nil, err
	}
	return &good.CartAddResponse{}, nil
}
